// 查看事件文档https://developers.weixin.qq.com/miniprogram/dev/api/media/editor/EditorContext.html
import WxValidate from '../../utils/WxValidate';
const {
  request
} = require("../../utils/index.js")
const app = getApp();
Page({
  data: {
    min: 0,
    max: 500,
    currentWordNumber: '',
    chooesList: [], //视频地址
    chooesID: [], //视频id
    chooesnumber: '', //视频数量
    shareshow: true, //是否可继续添加图片
    chooesshow: true, //是否可继续添加视频
    
    /* 上传多张图片开始 */
    count: 9, //最多选择图片的张数，默认9张
    uploadUrl: { //图片上传的服务器路径
      type: String,
      value: 'https://tms.sds.com.cn:8300/hw/upload/files'
    },
    showUrl: { //图片的拼接路径
      type: String,
      value: ''
    },
    detailPics: [], //上传的结果图片集合
    detailPicsID:[]
    /* 上传多张图片结束 */
  },

  //字数限制
  inputs: function (e) {
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.max) return;

    this.setData({
      currentWordNumber: len
    });
  },
  // 上传视频
  chooseVideo: function (e) {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      camera: 'back',
      maxDuration: 60, //视频最大大小
      success: res => {
        var tempFilePaths = res.tempFilePath;
        wx.uploadFile({
          url: 'https://tms.sds.com.cn:8300/hw/upload/files',
          filePath: tempFilePaths,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data',
          },
          formData: {
            method: 'POST',
            token: wx.getStorageSync('token'),
            sortVal: 1,
            updFileModule: 'business_wire',
            updFileType: 'video',
          },
          success(res2) {
            var res = JSON.parse(res2.data)
            if (res.status == 100) {
              that.setData({
                chooesList: res.data.updUrl,
                chooesID: res.data.updId,
                shareshow: false,
                chooesshow: false
              })
            }
          }
        })
      }
    })
  },

  // 视频展示
  chooseshow: function (e) {
    var that = this;
    console.log(12312);
    wx.previewMedia({
      success: this.data.chooesList,
      current: 0,
      type: 'video',
      url: this.data.chooesList[0]
    })
  },

  // 视频删除
  choosedele: function (e) {
    this.setData({
      chooesList: [],
      chooesshow: true,
      shareshow: true
    })
  },

  /* 上传多张图片开始 */
  shareUpload: function (e) {
    var that = this;
    var pics = [];
    that.setData({
      count:9
    })
    that.data.count = that.data.count - that.data.detailPics.length
    wx.chooseImage({
      count: that.data.count, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths; //图片临时地址
        for (var i = 0; i < imgs.length; i++) {
          pics.push(imgs[i])
        }
        that.uploadimg({
          url: that.data.uploadUrl, //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      }
    })
  },
  //多张图片上传
  uploadimg: function (data) {
    wx.showLoading({
      title: '上传中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url.value,
      filePath: data.path[i],
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data',
      },
      formData: {
        method: 'POST',
        token: wx.getStorageSync('token'),
        sortVal: 1,
        updFileModule: 'business_wire',
        updFileType: 'pic',
      },
      success: (resp) => {
        wx.hideLoading();
        var str = resp.data //返回的结果，可能不同项目结果不一样
        var pic = JSON.parse(str);
        var pic_name = pic.data;
        var detailPics = that.data.detailPics;
        detailPics.push(pic_name)
        this.data.detailPicsID.push(pic.data.updId)
        that.setData({
          detailPics: detailPics
        })
      },
      fail: (err) => {
        console.log(err)
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        if (that.data.detailPics.length == 1) {
          that.setData({
            chooesshow: false
          })
        }
        if (that.data.detailPics.length == 9) {
          that.setData({
            shareshow: false
          })
        }
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用   
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
          var myEventDetail = {
            picsList: that.data.detailPics
          } // detail对象，提供给事件监听函数
          var myEventOption = {} // 触发事件的选项
          that.triggerEvent('myevent', myEventDetail, myEventOption)
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimg(data);
        }
      }
    })
  },
  // 多图上传删除
  sharedele:function(e){
    var newList = [];
    var detailPics = this.data.detailPics;
    for (let i = 0; i < detailPics.length; i++) {
      if (i == e.currentTarget.dataset.index) {
        continue;
      } else {
        newList.push(detailPics[i])
      }
    }
    if (detailPics.length - 1 == 0) {
      this.setData({
        chooesshow: true
      })
      console.log(this.data.chooseshow)
    }
    this.setData({
      count: this.data.count - 1,
      detailPics: newList,
      shareshow: true,
    })
  },
  //多图上传查看
  shareshow: function (e) {
    var that = this;
    var urlList=[];
    var detaurllist = that.data.detailPics
   for(var i=0;i<detaurllist.length;i++){
     urlList.push(detaurllist[i].updUrl);
   }
    wx.previewImage({
      urls: urlList,
      current: urlList[e.currentTarget.dataset.id]
    })
  },
  /* 上传多张图片结束 */

  // 非空验证
  initValidate() {
    const rules = {
      title: {
        required: true,
      },
      shareContent: {
        required: true,
      },
    }
    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      title: {
        required: '请输入标题',
      },
      shareContent: {
        required: '请输入正文',
      }
    };
    // 创建实例对象
    this.WxValidate = new WxValidate(rules, messages)
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  //提交
  async submitForm(e) {
    let that = this;
    //非空验证
    const params = e.detail.value
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    // 验证通过以后->
    if (this.data.chooesID == '') { //视频为空
      this.setData({
        file: this.data.detailPicsID
      })
    } else {
      let arrayfile = [];
      arrayfile.push(this.data.chooesID.toString());
      this.setData({
        file: arrayfile
      })
    }
    if (this.data.chooesList == '' && this.data.detailPics == '') {
      wx.showToast({
        title: '请上传图片或视频',
        icon: 'none'
      })
    } else {
      let parm = {
        url: 'hw/portal/articles/business_wire/save?token=' + wx.getStorageSync('token'),
        data: {
          content: params.shareContent, //内容
          startTime: '2020-01-01 12:00',
          endTime: '2020-09-01 12:00',
          files: this.data.file, //文件
          title: params.title, //标题
        },
        method: 'POST',
        header: {
          'content-type': 'application/json', // 默认值
        },
      }
      let data = await request(parm);
      if (data.status == 100) {
        wx.showModal({
          title: '发布成功！',
          confirmText: "确认",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateBack({
                delta: 1,
              })
            }
          }
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initValidate();
  },
})